/**
 * @author fingerskier
 * This plugin provides functionality for a local AIR-SQLite database through jQuery
 * we are essentially 
	
example:

	the HTML markup:
		<query id="myQuery">
			SELECT	*
			FROM	ghleern
			WHERE	ID = ?
		</query>

	the javascript:
		$("#myQuery").query(4);
		
	the result:
		get all columns from the table ghleern where ID == 4
		
 *	NOTE: we are looping through the jQuery collection, just for goodlies
 *	...but I can't imagine that you would ever have multiple queries all requiring the same paramters...but who knows
 */

// pass in jQuery and the AIR DB
(function($, DB, AIR) {
	var console = console || air.Introspector.Console;
	
	$.fn.query = function() {
		// pass in DB params as arguments and store them to send to the iterator
		var params = arguments;
		var argLen = params.length;
		
		this.each(function() {
			var sqlStmt = new air.SQLStatement();
			
			$(this).data("DBquery", sqlStmt);	// setup the SQLite connection
			sqlStmt = $(this).data("DBquery");
			
			// link our SQL statement with the DB
			sqlStmt.sqlConnection = DB;
			
			// success callback for the SQL call
			sqlStmt.addEventListener(air.SQLEvent.RESULT, function(event) {
				// displays the result of the DB statement
				console.info("SQLite transcation");
				$(this).data("DBresult", sqlStmt.getResult().data);
				console.dump($(this).data("DBresult"));
			});
			
			// error callback for the SQL call
			sqlStmt.addEventListener(air.SQLErrorEvent.ERROR, function(event) {
				// displays any DB error
				console.error("SQLite error");
				console.dump(event);
			});
			
			// the initial query text
			sqlStmt.text = $(this).html();
			
			// cycle through arguments and replace the parameters with the given values
			for (var I = 0, len = argLen; I < len; I++) {
				sqlStmt.parameters[I] = params[I];
			}
			
			// unlike the previous version...
			//	we're assuming the collection to have only 1 element
			sqlStmt.execute();
		});
		
		// return the collection
		return this;
	}
	
	// this function cannot be chained
	// it returns the data from the previous query made on this object
	$.fn.queresult = function() {
		$(this).data("DBresult");
	}
})(jQuery, visionDB, air)
